package link.luyu.demo.port;

import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Map;
import java.util.Random;
import link.luyu.protocol.algorithm.SignatureAlgorithm;
import link.luyu.protocol.algorithm.ecdsa.secp256k1.EcdsaSecp256k1WithSHA256;

public class Tool {
    public static SecureRandom sr = new SecureRandom();
    public static Random random = new Random();

    static void generateEcdsaSecp256k1WithSHA256() {
        SignatureAlgorithm signer = new EcdsaSecp256k1WithSHA256();
        Map.Entry<byte[], byte[]> keyPair = signer.generateKeyPair();
        byte[] pubKey = keyPair.getKey();
        byte[] secKey = keyPair.getValue();

        System.out.print("seckey: [");
        for (int i = 0; i < secKey.length; i += 1) {
            int b = secKey[i];
            if (b < 0) {
                b += 256;
            }
            if (i == 0) {
                System.out.print("" + b);
            } else {
                System.out.print(", " + b);
            }
        }
        System.out.println("]");

        System.out.print("pubkey: [");
        for (int i = 0; i < pubKey.length; i += 1) {
            int b = pubKey[i];
            if (b < 0) {
                b += 256;
            }
            if (i == 0) {
                System.out.print("" + b);
            } else {
                System.out.print(", " + b);
            }
        }
        System.out.println("]");
    }

    public static String sha256(final String base) {
        try {
            final MessageDigest digest = MessageDigest.getInstance("SHA-256");
            final byte[] hash = digest.digest(base.getBytes("UTF-8"));
            final StringBuilder hexString = new StringBuilder();
            for (int i = 0; i < hash.length; i++) {
                final String hex = Integer.toHexString(0xff & hash[i]);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public static long randomNonce() {
        long n = random.nextInt();
        if (n < 0) {
            n = -n;
        }
        return n;
    }
}
